use slint::spawn_local;
use sql2doc_core::{run, ExportType, SqlConfig, SqlType};
slint::include_modules!();

fn main() {
    let app = App::new().unwrap();
    let weak_app = app.as_weak();
    app.global::<Confirm>().on_confirm(move |config| {
        let mysql_config = SqlConfig {
            host: config.host.to_string(),
            port: config.port.to_string().parse::<u16>().unwrap_or(3306),
            user: config.user.to_string(),
            password: config.password.to_string(),
            database: config.database.to_string(),
            output: None,
        };
        let tokio_runtime = tokio::runtime::Runtime::new().unwrap();
        let res = weak_app.upgrade().unwrap();
        res.set_open(true);
        res.set_message("运行中...".into());
        let sql_type = config.sqltype.to_string().to_lowercase();
        let sql_type = match sql_type.as_str() {
            "mysql" => SqlType::Mysql,
            "sql server" => SqlType::Mssql,
            _ => SqlType::Mysql,
        };
        let export = config.export.to_string().to_lowercase();
        let export = match export.as_str() {
            "word" => ExportType::Docx,
            "markdown" => ExportType::Markdown,
            "html" => ExportType::Html,
            "excel" => ExportType::Excel,
            _ => ExportType::Docx,
        };
        let _ = spawn_local(async move {
            let result = tokio_runtime
                .spawn(async move { run(sql_type, &mysql_config, export).await })
                .await
                .unwrap();
            result.map_or_else(
                |err| {
                    res.set_message(err.to_string().into());
                    res.set_btn_open(true);
                },
                |path| {
                    let message = format!("文件保存为:{}", path);
                    res.set_message(message.into());
                    res.set_btn_open(true);
                },
            )
        });
    });
    app.run().unwrap();
}
